package com.tyq.auth.security.service.impl;

import com.tyq.auth.security.exception.NonUserException;
import com.tyq.auth.security.exception.UserNameException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * 自定义登录实现类
 *
 * @author 谭永强
 * @date 2024-05-20
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    /**
     * 自定义用户查询
     *
     * @param username 用户名
     * @return 用户信息
     * @throws UsernameNotFoundException 用户不存在异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (ObjectUtils.isEmpty(username)) {
            throw new NonUserException("用户名不能为空!");
        }
        //1.查询数据库，判断用户是否存在，如果不存在则抛出UsernameNotFoundException异常。
        if (!"admin".equals(username)) {
            throw new UserNameException("用户名不存在!");
        }
        //2.用户存在，把查询出来的密码(密文)进行解析或者放入User构造方法中
        //模拟数据库中查询出来的密文。原密码(111111)
        String password = "$2a$10$.vxaUI63pE9z76k8DtThRevQBzt/6N9SfHGEtbes3vMRwo/Usyzdq";
        //模拟用户权限
        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal");
        //账户未过期
        boolean isAccountNonExpired = true;
        //账户未锁定
        boolean isAccountNonLocked = true;
        //密码未过期
        boolean isCredentialsNonExpired = true;
        //账户可用
        boolean isEnabled = true;
        //注意：该User为security提供的类或者实现了UserDetails接口的类
        return new User(username, password, isAccountNonExpired, isAccountNonLocked, isCredentialsNonExpired, isEnabled, grantedAuthorities);
    }
}
